package ltd.dujiabao.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ltd.dujiabao.commonutils.ResultCode;
import ltd.dujiabao.eduservice.entity.EduChapter;
import ltd.dujiabao.eduservice.entity.EduVideo;
import ltd.dujiabao.eduservice.entity.chapter.ChapterVo;
import ltd.dujiabao.eduservice.entity.chapter.VideoVo;
import ltd.dujiabao.eduservice.mapper.EduChapterMapper;
import ltd.dujiabao.eduservice.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ltd.dujiabao.eduservice.service.EduVideoService;
import ltd.dujiabao.servicebase.exception.MyException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author dujiabao
 * @since 2021-04-21
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
  @Autowired
  EduVideoService eduVideoService;

  @Override
  public Collection<ChapterVo> getChapterVideoTree(String courseId) {
    QueryWrapper<EduChapter> wrapper = new QueryWrapper<EduChapter>();
    wrapper.eq("course_id", courseId);
    // 查询出该课程的所有章节和小节
    List<EduChapter> eduChapterList = list(wrapper);
    List<EduVideo> eduVideoList = eduVideoService.list(new QueryWrapper<EduVideo>().eq("course_id", courseId));
    HashMap<String, ChapterVo> map = new LinkedHashMap<>();
    for (EduChapter eduChapter : eduChapterList) {
      ChapterVo chapterVo = new ChapterVo();
      BeanUtils.copyProperties(eduChapter, chapterVo);
      map.put(eduChapter.getId(), chapterVo);
    }

    for (EduVideo eduVideo : eduVideoList) {
      VideoVo videoVo = new VideoVo();
      BeanUtils.copyProperties(eduVideo, videoVo);
      map.get(eduVideo.getChapterId()).addChild(videoVo);
    }
    return map.values();
  }

  @Override
  public boolean removeChapter(String id) {
    int count = eduVideoService.count(new QueryWrapper<EduVideo>().eq("chapter_id", id));
    if (count > 0) throw new MyException(ResultCode.FAILURE, "该章节包含有小节，若要删除该章节，请先删除其余小节");  // 如果旗下还有小节，那就不能删
    return removeById(id);
  }

  @Override
  public boolean removeByCourseId(String courseId) {
    QueryWrapper<EduChapter> wrapper = new QueryWrapper<EduChapter>().eq("course_id",courseId);
    return remove(wrapper);
  }
}
